#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h> 
#include<arpa/inet.h>
#include<unistd.h>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include"Common.hpp"
// ./client_tcp server_ip server_port
const char*server_ip = "127.0.0.1";
int server_port=8080;
int main()
{
    //创建套接字
    int socket=::socket(AF_INET,SOCK_STREAM,0);
    if(socket<0)
    {
        std::cout<<"create socket error"<<std::endl;
        exit(1);
    }

    //连接服务器
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=::htons(server_port);
    server.sin_addr.s_addr=::inet_addr(server_ip);
    int n=::connect(socket,CONV(&server),sizeof(server));
    if(n<0)
    {
        std::cout<<"connect error"<<std::endl;
        exit(2);
    }
    while(true)
    {
        std::string input;
        std::cout<<"input message:";
        std::getline(std::cin,input);

        int n=::write(socket,input.c_str(),input.size());
        if(n<=0)
        {
            continue;
        }
        char inbuffer[1024];
        n=::read(socket,inbuffer,sizeof(inbuffer));
        if(n>0)
        {
            inbuffer[n]=0;
            std::cout<<inbuffer<<std::endl;
        }
    }
    ::close(socket);
    return 0;
}